import Root, {getPages} from './root';
import {map} from '../../util/tree';
import make from '../schema-factory';
import * as find from 'lodash/find';
import * as React from 'react'

import './dashboard';
import './news/index';
import './data_statistic/index';
import './platform/index'
import './org/index';
import './team/index';
import './project/index';
import './financial_management/index';
import './star_certification/index';
import './score_mall/index';
import './volunteer/index';
import './safe_plan/index';
import './feeling_tone/index';
import './good_example/index';
import './claim_project/index';
import './third';
import './user/index';
import './banner/index';
import './module/index';
import './setting/index';


export function getRoute() {
  return {
    component: Root,
    childRoutes: map(getPages(), item => {
      const route = {
        ...item,
        path: item.path
      };

      if (item.schema || item.component) {
        route.component = make(item, item.title || item.label);
      }
      return route;
    }, 'childRoutes', item => {
      if (item.childRoutes && item.childRoutes.length && item.childRoutes[0].component) {
        item.indexRoute = {
          // component: item.childRoutes[0].component
          component: selectFirstChild(item.childRoutes)
        }
      }
    })
  }
}

function selectFirstChild(childRoutes) {
  return class extends React.Component {
    static contextTypes = {
      can: React.PropTypes.func
    };

    render() {
      const route = find(childRoutes, item => (item.component || item.indexRoute && item.indexRoute.component) && (!item.acl || this.context.can(item.acl)));

      if (!route) {
        return (
          <div className="container w-xxl w-auto-xs">
            <div className="text-center m-b-lg">
              <h1 className="text-shadow text-white">403</h1>
            </div>
            <div className="text-center">
              <p className="text-muted">权限不够</p>
            </div>
          </div>
        );
      }

      const Component = (route.component || route.indexRoute && route.indexRoute.component);

      return <Component {...this.props} />
    }
  }
}
